<?php
/**
 * DESC:
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020/5/2
 */

namespace app\admin\controller;


use app\common\controller\AdminUserBase;
use app\common\model\ArticleCate;
use app\common\model\ArticleCateRelated;
use think\Db;
use think\Exception;
use think\facade\Request;

class Article extends AdminUserBase
{
    /**
     * 内容分类
     */
    public function article_cate(){
        if (Request::isAjax()){
            $data = ArticleCate::order('sort asc')->append(['open'])->select();
            $this->result($data);
        }
        return view();
    }
    public function article_cate_tree(){
        $data = ArticleCate::order('sort asc')->select()->toArray();
        $this->result(array2tree($data));
    }
    public function article_cate_save(){
        $param = input();

        $articleCateModel = new ArticleCate();
        if (empty($param['id'])){
            $res = $articleCateModel->allowField(true)->isUpdate(false)->save($param);
            saveAdminLog("添加内容分类");
        }else{
            $res = $articleCateModel->allowField(true)->isUpdate(true)->save($param);
            saveAdminLog("编辑内容分类");
        }

        if ($res !== false){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function article_cate_del(){
        $id = input('id');
//        判断当前节点下有没有子节点
        $ziNum = Db::name('articleCate')->where('pid',$id)->count();
        if ($ziNum > 0){
            $this->error('当前节点下有子分类无法删除，请先删除子分类');
        }
        $res = Db::name('articleCate')->delete($id);
        if ($res !== false){
            saveAdminLog("删除内容分类");
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 内容分类
     */

    /**
     * 内容列表
     */
    public function article(){
        if (Request::isAjax()){
            $param = input();
            $where = [];
            $hasWhere = [];
            if (!empty($param['title'])){
                $where[] = ['title','like','%'.$param['title'].'%'];
            }
            if (!empty($param['article_cate_id'])){
                $hasWhere[] = ['article_cate_id','in',$param['article_cate_id']];
            }
            if (!empty($param['top'])){
                $where[] = ['top','=',$param['top']];
            }
            if (!empty($param['show'])){
                $where[] = ['show','=',$param['show']];
            }
            $data = \app\common\model\Article::hasWhere('cateRelated',$hasWhere)->where($where)->append(['cate_name'])->order('sort desc')->paginate($param['limit']);
            $data = $data->toArray();
            $this->result($data['data'],$data['total']);
        }
        return view('article/article/index');
    }
//    回收站
    public function recycle(){
        if (Request::isAjax()){
            $param = input();
            $where = [];
            if (!empty($param['title'])){
                $where[] = ['title','like','%'.$param['title'].'%'];
            }
            $data = \app\common\model\Article::onlyTrashed()->where($where)->order('sort desc')->paginate($param['limit']);
            $data = $data->toArray();
            $this->result($data['data'],$data['total']);
        }
        return view('article/article/recycle');
    }
    public function form(){
        $id = input('id');
        $data = \app\common\model\Article::get($id);
        if (!empty($data)){
            $data['cate_id'] = $data->cateRelated()->column('article_cate_id');
            $data['cate_id'] = json_encode($data['cate_id']);
        }
        $this->assign('data',$data);

        return view('article/article/form');
    }
    public function article_save(){
        $param = input();


        try {

            $articleModel = new \app\common\model\Article();
            if (empty($param['id'])){
                $param['admin_id'] = session('admin.id');
                $articleModel->allowField(true)->isUpdate(false)->save($param);
                if (isset($param['article_cate_id']) && is_string($param['article_cate_id'])){
                    $article_cate_id = explode(',',$param['article_cate_id']);
                    if (is_array($article_cate_id)){
                        $cate_ids = [];
                        foreach ($article_cate_id as $k=>$v){
                            $cate_ids[] = [
                                'article_cate_id'=>$v
                            ];
                        }
                        $articleModel->cateRelated()->saveAll($cate_ids);
                    }
                }
                saveAdminLog("添加文章内容");
            }else{
                $articleModel->allowField(true)->isUpdate(true)->save($param);
//                编辑的使用，使用中间件模型
                if (isset($param['article_cate_id']) && is_string($param['article_cate_id'])){
                    $article_cate_id = explode(',',$param['article_cate_id']);
//                    查询编辑之前的内容分类
                    $oldCategoryIds        = $articleModel->cate()->column('article_cate_id');
//                    查出来相同的内容分类
                    $sameCategoryIds       = array_intersect($article_cate_id, $oldCategoryIds);
//                    查询需要删除的内容分类
                    $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
//                    查询需要插入的内容分类
                    $newCategoryIds        = array_diff($article_cate_id, $sameCategoryIds);

//                    中间模型自动删除需要删除的分类
                    if (!empty($needDeleteCategoryIds)) {
                        $articleModel->cate()->detach($needDeleteCategoryIds);
                    }

//                    中间模型自动添加内容分类
                    if (!empty($newCategoryIds)) {
                        $articleModel->cate()->attach(array_values($newCategoryIds));
                    }
                }
                saveAdminLog("编辑文章内容");
            }

        }catch (\Exception $e){
            $this->error($e->getMessage().$e->getLine());
        }
        $this->success();
    }
    public function article_edit_save(){
        $param = input();
        $article = new \app\common\model\Article();
        $res = $article->allowField(true)->isUpdate(true)->save($param,['id'=>$param['id']]);
        if ($res !== false){
            saveAdminLog("编辑文章内容");
            $this->success();
        }else{
            $this->error();
        }
    }
//    软删除
    public function article_del(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
        $res = \app\common\model\Article::destroy($id);
        if ($res !== false){
            saveAdminLog("软删除内容");
            $this->success();
        }else{
            $this->error();
        }
    }
//    真实删除
    public function article_del_true(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
        Db::startTrans();
        try {
            Db::name('ArticleCateRelated')->where('article_id','in',$id)->delete();
            Db::name('article')->where('id','in',$id)->delete();
            saveAdminLog("真实删除内容");
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success(1);
    }
    public function article_restore(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
        $res = Db::name('article')->where('id','in',$id)->update(['delete_time'=>0]);
        if ($res !== false){
            saveAdminLog("恢复回收站内容");
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 内容列表
     */
}
